package cn.edu.glut.user.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.glut.dto.UserIntro;
import cn.edu.glut.entity.Admin;
import cn.edu.glut.entity.Secretary;
import cn.edu.glut.entity.Student;
import cn.edu.glut.entity.Teacher;
import cn.edu.glut.entity.User;
import cn.edu.glut.exception.ServiceException;
import cn.edu.glut.user.repository.AdminRepository;
import cn.edu.glut.user.repository.SecretaryRepository;
import cn.edu.glut.user.repository.StudentRepository;
import cn.edu.glut.user.repository.TeacherRepository;
import cn.edu.glut.user.service.UserDetailService;
/**
 * 
 * @author Caizhfy
 * @email caizhfy@163.com
 * @createTime 2017年12月9日
 * @description 
 *
 */
@Service
public class UserDetailServiceImpl implements UserDetailService {
	@Autowired
	private StudentRepository sRepository;
	@Autowired
	private AdminRepository aRepository;
	@Autowired
	private TeacherRepository tRepository;
	@Autowired
	private SecretaryRepository seRepository;

	//用户登录
	@Override
	public User toLogin(String username, String password, int userType) {
		// TODO Auto-generated method stub
		User u = null;
		switch (userType) {
		case TYPE_STUDENT:
			u = sRepository.findByUsername(username);
			break;
		case TYPE_TEACHER:
			u = tRepository.findByUsername(username);
			break;
		case TYPE_SECRETARY:
			u = seRepository.findByUsername(username);
			break;
		case TYPE_ADMIN:
			u = aRepository.findByUsername(username);
			break;
		}
		if (u != null && u.getPassword().equals(password)){
			u.setUserType(userType);
			return u;
		}

		return null;
	}

	//修改密码
	@Override
	public int changePassword(UserIntro user, String oldPwd, String newPwd) {
		if(StringUtils.isEmpty(oldPwd)||StringUtils.isEmpty(newPwd))
			return 0;
		switch (user.getUserType()) {
		case TYPE_STUDENT:
			Student s = sRepository.findOne(user.getId());
			if(!s.getPassword().equals(oldPwd))
				throw new ServiceException("旧密码不正确");
			sRepository.save((Student)s.setPassword(newPwd));
			break;
		case TYPE_TEACHER:
			Teacher t = tRepository.findOne(user.getId());
			if(!t.getPassword().equals(oldPwd))
				throw new ServiceException("旧密码不正确");
			tRepository.save((Teacher)t.setPassword(newPwd));
			break;
		case TYPE_SECRETARY:
			Secretary se = seRepository.findOne(user.getId());
			if(!se.getPassword().equals(oldPwd))
				throw new ServiceException("旧密码不正确");
			seRepository.save((Secretary)se.setPassword(newPwd));
			break;
		case TYPE_ADMIN:
			Admin a = aRepository.findOne(user.getId());
			if(!a.getPassword().equals(oldPwd))
				throw new ServiceException("旧密码不正确");
			aRepository.save((Admin)a.setPassword(newPwd));
			break;
		}
		return 1;
	}

}
